﻿//
// Copyright © MixModes Inc. 2011
//

using System.Collections.Generic;
using Microsoft.Phone.Shell;

namespace MixModes.Phone.Synergy.Framework
{
    /// <summary>
    /// Transitent data store
    /// </summary>
    internal class TransientDataStore : IDataStore
    {        
        /// <summary>
        /// Stores the value in the data storage corresponding to the specified key
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <returns>True if data was stored successfully, False otherwise</returns>
        public bool Store(string key, object value)
        {
            if ((string.IsNullOrEmpty(key)) || (value == null))
            {
                return false;
            }

            IDictionary<string, object> dataStore = PhoneApplicationService.Current.State;
            dataStore[key] = value;

            return true;
        }

        /// <summary>
        /// Retrieves the value in the data store corresponding to the specified key
        /// </summary>
        /// <typeparam name="T">Type of value</typeparam>
        /// <param name="key">The key.</param>
        /// <returns>Value corresponding to the key if there is one; default value otherwise</returns>
        public T Retrieve<T>(string key)
        {
            IDictionary<string, object> dataStore = PhoneApplicationService.Current.State;
            object value;

            if ((!dataStore.TryGetValue(key, out value)) && (!(value is T)))
            {
                return default(T);
            }

            return (T)value;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            // Do nothing
        }
    }
}
